import { createContext, useContext, use, Suspense } from "react";
import { ErrorBoundary } from "react-error-boundary";

const ThemeContext = createContext(null);
function MyContext({ show }) {
  if (show) {
    const theme = useContext(ThemeContext);
    const theme2 = use(ThemeContext);

    return (
      <div>
        Theme is {theme}/{theme2}
      </div>
    );
  }
  return null;
}

function fetchMessage() {
  return new Promise((resolve, reject) => {
    setTimeout(
      () => (Math.random() > 0.2 ? resolve("请求成功") : reject()),
      1000
    );
  });
}

function MessageComponent({ messagePromise }) {
  // const messagePromise1 = fetchMessage();  //必须是上层组件传递的promise 否则不生效
  const message = use(messagePromise); // 使用 use 读取 Promise
  return <p>{message}</p>;
}

function UseValue() {
  const messagePromise = fetchMessage(); // 获取数据
  return (
    <>
      <ThemeContext.Provider value="dark">
        <MyContext show={true} />
      </ThemeContext.Provider>
      <ErrorBoundary fallback={<p>⚠️Something went wrong</p>}>
        <Suspense fallback={<div>Loading...</div>}>
          <MessageComponent messagePromise={messagePromise} />
        </Suspense>
      </ErrorBoundary>
    </>
  );
}

export default UseValue;
